package client.Thread;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;

import remoteStack.RemoteImp;
import remoteStack.RemoteInt;

import manager.MyState;

public class ConnectThread extends Thread {

	private MyState my;
	private int tentativi = 0;

	public ConnectThread() {

		my = MyState.getInstance();

	}

	public void run() {

		int myId = my.getId();

		try {

			RemoteImp ri = new RemoteImp();

			String MyServer = "//" + my.getMyIp() + ":" + my.getMyPort() + "/node" + myId;

			System.out.println("myServer " + MyServer);

			if (System.getSecurityManager() == null) {
				System.setSecurityManager(new RMISecurityManager());
			}

			Naming.rebind(MyServer, ri);

			Thread.sleep(15000);

			if(connectNextClient(tentativi)){
				if(my.getRuolo().equals("mazziere"))
					{
					my.getInterfaceNextClient().inizioGioco(my.getname());
					
					}
				
			}else{
				
	
				
				
				
			}

		} catch (RemoteException e) {

			e.printStackTrace();
		} catch (MalformedURLException e) {

			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	
	public boolean connectNextClient(int tentativi) {
		boolean result=true;
	
		String urlNextClient;

		if (tentativi == 5) {
			
			if (my.removeClient()) {
				tentativi = 0;
				connectNextClient(tentativi);
			} else{
				System.out.println("sono solo");
				result = false;
			}

		} else {
			

			urlNextClient = my.getUrlNextClient();
			
			try {
				Thread.sleep(5000);
				
				RemoteInt ri;
				System.out.println("next server " + urlNextClient);
				
				ri = (RemoteInt) Naming.lookup(urlNextClient);
				
				System.out.println("effettuato lookup nodo " + urlNextClient);
				my.setInterfaceNextClient(ri);
				tentativi = 0;
				result =true;

			} catch (RemoteException e) {
				
				tentativi+=1;
				System.out.println("Tentativo di connessione: "+tentativi + " non riuscito");
				connectNextClient(tentativi);
				//e.printStackTrace();		
				
			} catch (MalformedURLException e) {
				
				tentativi+=1;
				System.out.println("Tentativo di connessione: "+tentativi + "non riuscito");
				connectNextClient(tentativi);
			
			} catch (NotBoundException e) {
				tentativi+=1;
				System.out.println("Tentativo di connessione: "+tentativi + "non riuscito");
				connectNextClient(tentativi);
			
				//e.printStackTrace();
				
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return result;
	}

}
